package com.example.gorannet;

import static com.example.gorannet.TicketDetailsActivity.employee_id;
import static com.example.gorannet.TicketDetailsActivity.ticket_date;
import static com.example.gorannet.TicketDetailsActivity.ticket_no;
import static com.example.gorannet.TicketDetailsActivity.act;
import static com.example.gorannet.TicketDetails.employee_idf;
import static com.example.gorannet.TicketDetails.ticket_datef;
import static com.example.gorannet.TicketDetails.ticket_nof;
import static com.example.gorannet.TicketDetails.fra;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.CornerPathEffect;
import android.graphics.DashPathEffect;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.AttributeSet;
import android.util.Base64;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

@SuppressLint({
		"NewApi", "DrawAllocation"
})
public class CaptureSignature extends Activity
{
	private signature						mSignature;
	private LinearLayout					mContent;
	private BootstrapButton							clear, save;
	private String							evaluated,comVal, unVal, profVal, timeVal;
	private static final String		survey_url	= "http://db.gorannet.net/DB/Technical/tickets/evaluation.php";
	private ConnectionDetector		connectionDetector;
	private DBHandler				dbHandler;
	private Bitmap							returnedBitmap;
	private Drawable						bgDrawable;
	private ByteArrayOutputStream	stream;
	private String emp_id = "", tct_no = "";
	private long tct_date = 0;
	static Class<?> device = null;
    static Class<MyListItems> tablet = MyListItems.class;
    static Class<MyChoicesActivity> mobile = MyChoicesActivity.class;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.capturesignature);
		save = (BootstrapButton) findViewById(R.id.save);
		save.setEnabled(false);
		clear = (BootstrapButton) findViewById(R.id.clear);
		clear.setEnabled(true);
		mContent = (LinearLayout) findViewById(R.id.mysignature);
		mSignature = new signature(this, null);
		mContent.addView(mSignature);
		Intent in = getIntent();
		evaluated = in.getStringExtra("doeval");
		comVal = in.getStringExtra("comm");
		unVal = in.getStringExtra("understand");
		profVal = in.getStringExtra("prof");
		timeVal = in.getStringExtra("timeV");
		dbHandler = new DBHandler(getApplicationContext());
		connectionDetector = new ConnectionDetector(getApplicationContext());
		if(act == 0 && fra == 1)
		{
			emp_id = employee_idf;
			tct_no = ticket_nof;
			tct_date = ticket_datef;
		}
		else
			if(act == 1 && fra == 0)
			{
				emp_id = employee_id;
				tct_no = ticket_no;
				tct_date = ticket_date;
			}
		
		save.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				mSignature.save();
				boolean deviceType = isTablet(getApplicationContext());
				if(deviceType == true){
		            device = tablet;
		        }else
		            if(deviceType == false)
		            {
		                device = mobile;
		            }
				byte[] byteImageBytes = stream.toByteArray();
				if (connectionDetector.isConnectingToInternet())
				{					
					
					String strImageString = Base64.encodeToString(byteImageBytes, Base64.DEFAULT);
					try
					{
						post(survey_url,ticket_no, strImageString);
						dbHandler.insertTicketSurvey(ticket_no,employee_id,comVal,unVal,profVal,timeVal,ticket_date,byteImageBytes, "1");
						Toast.makeText(getApplicationContext(), "Thank you", Toast.LENGTH_LONG).show();
				        Intent i = new Intent(getApplicationContext(), device);
                        startActivity(i);                       
					}
					catch (Exception e)
					{
						Toast.makeText(getApplicationContext(),"post() exception: " + e.toString(), Toast.LENGTH_LONG).show();
					}
					 
					
				}

				if (!connectionDetector.isConnectingToInternet())
				{
					try
					{
					dbHandler.insertTicketSurvey(ticket_no,employee_id,comVal,unVal,profVal,timeVal,ticket_date,byteImageBytes,"0");
					Intent i = new Intent(getApplicationContext(), device);
                    startActivity(i);
					}
					catch (Exception e)
					{
						Toast.makeText(getApplicationContext(),"post() exception: " + e.toString(), Toast.LENGTH_LONG).show();
					}
				}
			}
		});
		clear.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				mSignature.clear();
			}
		});
	}

	// This is the onClick method of the button for saving the image

	@SuppressLint("NewApi")
	public class signature extends View
	{
		static final float				STROKE_WIDTH		= 3f;
		static final float				HALF_STROKE_WIDTH	= STROKE_WIDTH / 2;
		Paint							paint				= new Paint();
		Path							path				= new Path();
		private static final int		MAXFINGERS			= 20;
		private Bitmap					mBitmap;
		private Canvas					mCanvas;
		private final Rect				mRect				= new Rect();
		private final Paint				mPaint;
		private float					mCurX;
		private float					mCurY;
		private float[]					mPrevX				= new float[MAXFINGERS];			
		private float[]					mPrevY				= new float[MAXFINGERS];
		public boolean					bShowSamples		= true;
		float							lastTouchX;
		float							lastTouchY;
		final RectF						dirtyRect			= new RectF();
		Window							window				= getWindow();

		public signature(Context context, AttributeSet attrs)
		{
			super(context, attrs);
			mPaint = new Paint();
			setFocusable(true);
			setFocusableInTouchMode(true);
			mPaint.getFlags();
			mPaint.setAntiAlias(true);
			mPaint.setColor(Color.BLACK);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setStyle(Style.FILL);
			mPaint.setStrokeWidth(STROKE_WIDTH);
			mPaint.setStrokeJoin(Paint.Join.BEVEL);
			mPaint.setTypeface(Typeface.DEFAULT_BOLD);
			mPaint.setFilterBitmap(true);
			mPaint.setDither(true);
			mPaint.setStrokeJoin(Paint.Join.MITER);
			mPaint.setStrokeMiter(HALF_STROKE_WIDTH);
			mPaint.setPathEffect(new CornerPathEffect(0));
			mPaint.setFilterBitmap(true);
			Paint mPaint = new Paint();
			mPaint.setDither(true);
			MaskFilter m = new MaskFilter();
			mPaint.setMaskFilter(m);
		}

		public void clear()
		{
			mBitmap.eraseColor(Color.WHITE);
			invalidate();
			save.setEnabled(false);
		}

		public void save()
		{
			
			returnedBitmap = Bitmap.createBitmap(mContent.getWidth(),
					mContent.getHeight(), Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(returnedBitmap);
			bgDrawable = mContent.getBackground();
			if (bgDrawable != null)
			{
				bgDrawable.draw(canvas);
			}
			else
			{
				canvas.drawColor(Color.WHITE);
			}
			mContent.draw(canvas);
			stream = new ByteArrayOutputStream();
			returnedBitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
			
		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh)
		{
			int curW = mBitmap != null ? mBitmap.getWidth() : 0;
			int curH = mBitmap != null ? mBitmap.getHeight() : 0;
			if (curW >= w && curH >= h)
			{
				return;
			}

			if (curW < w) curW = w;
			if (curH < h) curH = h;

			Bitmap newBitmap = Bitmap.createBitmap(curW, curH,
					Bitmap.Config.ARGB_8888);
			newBitmap.eraseColor(Color.WHITE); /* screen goes white */
			Canvas newCanvas = new Canvas();
			newCanvas.setBitmap(newBitmap);
			if (mBitmap != null)
			{
				newCanvas.drawBitmap(mBitmap, 0, 0, null);
			}
			mBitmap = newBitmap;
			mCanvas = newCanvas;

			/*
			 * initialize previous finger locations so we know later they need
			 * to be filled for the first time
			 */
			for (int finger = 1; finger < MAXFINGERS; finger++)
			{
				mPrevX[finger] = -100;
				mPrevY[finger] = -1;
			}
		}

		@Override
		protected void onDraw(Canvas canvas)
		{
			canvas.drawColor(Color.WHITE);
			paint.setStrokeWidth(STROKE_WIDTH);
			mPaint.setStrokeJoin(Paint.Join.BEVEL);

			paint.setAntiAlias(true);

			paint.setPathEffect(new DashPathEffect(new float[]
			{
					8, 8
			}, 0));

			if (mBitmap != null)
			{
				canvas.drawBitmap(mBitmap, 0, 0, paint);
				mBitmap.setHasAlpha(true);
			}
		}

		@SuppressLint("NewApi")
		@Override
		public boolean onTouchEvent(MotionEvent event)
		{
			float eventX = event.getX();
			float eventY = event.getY();
			int action = event.getActionMasked();
			int numPtrs;
			save.setEnabled(true);
			switch (action)
			{
				case MotionEvent.ACTION_DOWN: /* primary pointer */
				case MotionEvent.ACTION_POINTER_DOWN: /* any subsequent pointer */
					numPtrs = event.getPointerCount();
					for (int finger = 0; finger < numPtrs; finger++)
					{
						mPrevX[finger] = mPrevY[finger] = -1;
					}
					break;
				case MotionEvent.ACTION_MOVE: /* any number of pointers move */
					int N = event.getHistorySize();
					numPtrs = event.getPointerCount();
					for (int histndx = 0; histndx < N; histndx++)
					{
						for (int finger = 0; finger < numPtrs; finger++)
						{
							mCurX = event.getHistoricalX(finger, histndx);
							mCurY = event.getHistoricalY(finger, histndx);
							drawPoint(
									mCurX,
									mCurY,
									event.getHistoricalPressure(finger, histndx),
									event.getHistoricalSize(finger, histndx),
									finger);
						}
					}
					for (int finger = 0; finger < numPtrs; finger++)
					{
						mCurX = event.getX(finger);
						mCurY = event.getY(finger);
						drawPoint(mCurX, mCurY, event.getPressure(finger),
								event.getSize(finger), finger);
					}
					break;
				case MotionEvent.ACTION_POINTER_UP:
				case MotionEvent.ACTION_UP: /* all pointers are up */
					resetDirtyRect(eventX, eventY);
					int historySize = event.getHistorySize();
					for (int i = 0; i < historySize; i++)
					{
						float historicalX = event.getHistoricalX(i);
						float historicalY = event.getHistoricalY(i);
						path.lineTo(historicalX, historicalY);
					}
					path.lineTo(eventX, eventY);
					break;
				case MotionEvent.ACTION_CANCEL:

					for (int finger = 0; finger < MAXFINGERS; finger++)
					{
						mPrevX[finger] = -1;
						mPrevY[finger] = -1;
					}

					break;
			}
			invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
					(int) (dirtyRect.top - HALF_STROKE_WIDTH),
					(int) (dirtyRect.right + HALF_STROKE_WIDTH),
					(int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

			lastTouchX = eventX;
			lastTouchY = eventY;

			return true;
		}

		private void resetDirtyRect(float eventX, float eventY)
		{
			dirtyRect.left = Math.min(lastTouchX, eventX);
			dirtyRect.right = Math.max(lastTouchX, eventX);
			dirtyRect.top = Math.min(lastTouchY, eventY);
			dirtyRect.bottom = Math.max(lastTouchY, eventY);
		}

		private void drawLine(int finger)
		{
			paint.setColor(Color.BLACK);

			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeJoin(Paint.Join.ROUND);
			paint.setStrokeWidth(STROKE_WIDTH);
			mCanvas.drawLine(mPrevX[finger], mPrevY[finger], mCurX, mCurY,
					mPaint);
		}

		private void drawPoint(float x, float y, float pressure, float width,
				int finger)
		{
			int lowX, lowY, highX, highY;
			if (mBitmap != null)
			{
				float radius = (float) 5.0;
				paint.setColor(Color.BLACK);
				paint.setStyle(Paint.Style.STROKE);
				paint.setStrokeJoin(Paint.Join.ROUND);
				paint.setStrokeWidth(STROKE_WIDTH);

				if ((mPrevX[finger] == -1 && mPrevY[finger] == -1))
				{ /* we don't need to draw a line */
					mPrevX[finger] = x;
					mPrevY[finger] = y;
					mRect.set((int) (x - 3 * radius), (int) (y - 3 * radius),
							(int) (x + 3 * radius), (int) (y + 3 * radius));
				}
				else
				{
					/*
					 * we do need to draw line as we have a valid previous
					 * location
					 */
					drawLine(finger);
					if (mPrevX[finger] <= mCurX)
					{
						lowX = (int) (mPrevX[finger] - 3 * radius);
						highX = (int) (mCurX + 3 * radius);
					}
					else
					{
						lowX = (int) (mCurX - 3 * radius);
						highX = (int) (mPrevX[finger] + 3 * radius);
					}

					if (mPrevY[finger] <= mCurY)
					{
						lowY = (int) (mPrevY[finger] - 3 * radius);
						highY = (int) (mCurY + 3 * radius);
					}
					else
					{
						lowY = (int) (mCurY - 3 * radius);
						highY = (int) (mPrevY[finger] + 3 * radius);
					}
					mRect.set(lowX, lowY, highX, highY);
					mPrevX[finger] = mCurX;
					mPrevY[finger] = mCurY;
				}

				invalidate(mRect);
			}
		}
	}

	
	private void post(String strURL, String strTicketID, String strSignature)
			throws IOException
	{
		try{
		JSONParser jsonParser = new JSONParser();
		List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("ticketID", tct_no));
        param.add(new BasicNameValuePair("userID", emp_id));
        param.add(new BasicNameValuePair("evaluated", evaluated));
        param.add(new BasicNameValuePair("communication", comVal));
        param.add(new BasicNameValuePair("understanding", unVal));
        param.add(new BasicNameValuePair("professionalism", profVal));
        param.add(new BasicNameValuePair("completeTime", timeVal));
        param.add(new BasicNameValuePair("ticketDate", tct_date+""));
        param.add(new BasicNameValuePair("signature", strSignature));     
        
		@SuppressWarnings("unused")
		JSONObject json = jsonParser.makeHttpRequest(strURL, "POST", param);
		}
		catch(Exception e){
		Toast.makeText(getApplicationContext(), "Poat not successed!!", Toast.LENGTH_LONG).show();
		}
		
		
	}
	//Determines If The Device is Tablet?!.....If it is Tablet it returns true
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }
}
